package com.butioy.study.jersey.handler;

import com.butioy.study.jersey.pojo.Result;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yanglq
 * @since 3.0.0
 */
@Slf4j
@Provider
@Singleton
public class ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String errorMsg = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));

        log.warn("请求参数校验失败, 失败信息: {}", errorMsg, e);

        Result<Object> failResp = Result.fail(1201, errorMsg);
        return Response.status(Response.Status.BAD_REQUEST).entity(failResp).build();
    }
}
